<script lang="ts" setup>
import RoomStatus from './components/roomStatus.vue';
import RoomAction from './components/RoomAction.vue';
import RoomMessage from './components/RoomMessage.vue';
import io, { Socket } from 'socket.io-client';
import { nextTick, onMounted, onUnmounted, provide, ref } from 'vue';
import { baseURL } from '@/utils/request';
import { useUserStore } from '@/stores';
import { useRoute } from 'vue-router';
import type { Message, TimeMessages } from '@/types/room';
import { MsgType, OrderType } from '@/enums';
import type { ConsultOrderItem, Image } from '@/types/consult';
import { getConsultOrederDetail } from '@/services/consult';
import dayjs from 'dayjs';
import { showToast } from 'vant';
// 建立连接
// const socket = io('http://localhost:3000')
// socket.on('connect',()=>{
//   console.log('连接成功')
//   // 发送消息
//   socket.emit('chat message','您好！socket.io')
// })
// socket.on('chat message',(msg)=>{
//   console.log('收到消息：',msg)
//   socket.close() // 关闭连接
// })
// socket.on('disconnect',()=>{
//   console.log('连接断开')
// })
const consult = ref<ConsultOrderItem>()
const loadConsult = async ()=>{
  const res =await getConsultOrederDetail(route.query.orderId as string)
  consult.value = res.data
  console.log(consult?.value.status !==OrderType.ConsultChat)
}
// 提供问诊数据给后代 组件
provide('consult',consult)
const completeEva = (score:number)=>{
  const item = list.value.find(item =>item.msgType===MsgType.CardEvaForm)
  if(item){
    item.msg.evaluateDoc = { score}
    item.msgType = MsgType.CardEva
  }
}
provide('completeEva',completeEva)
const store = useUserStore()
const route = useRoute()
const list = ref<Message[]>([])
const initalMsg = ref(true)
let socket:Socket
onMounted(()=>{
  loadConsult()
  socket = io(baseURL,{
    auth:{
      token: `Bearer ${store.user?.token}`
    },
    query:{
      orderId:route.query.orderId
    }
  })
  socket.on('connect',()=>{
    console.log('连接成功')
  })
  socket.on('disconnect',()=>{
    console.log('连接断开')
  })
  socket.on('error',(err)=>{
    console.error('连接错误:', err)
  })
  // 获取聊天记录，如果是第一次（默认消息）
  socket.on('chatMsgList',({data}:{data:TimeMessages[]})=>{
    // console.log('收到消息列表:', res)
    // data 数据==== > [{createTime},...items]
    const arr:Message[] = []
    data.forEach((item,i) => {
      // 记录每一段消息中最早的消息时间，获取历史消息中使用
      if(i===0) time.value = item.createTime
      arr.push({
        msgType:MsgType.Notify,
        msg:{
          content:item.createTime,
        },
        createTime:item.createTime,
        id:item.createTime
      })
      arr.push(...item.items)
    });
    // console.log('聊天记录:', arr)
    // 按照时间排序聊天信息
    const newArr = arr.sort((a, b) => {
      return new Date(a.createTime).getTime() - new Date(b.createTime).getTime()
    })

    list.value.unshift(...newArr)
    loading.value = false
    if(!arr.length) return showToast('没有更多聊天记录了！')
    if(initalMsg.value){
      socket.emit('updateMsgStatus',arr[arr.length-1].id)
      // 第一次需要滚动到最新消息
      scrollToBottom()
      initalMsg.value = false
    }
  })
  // 监听订单状态的变化
  socket.on('statusChange',()=>loadConsult())
  // 接受聊天消息
  socket.on('receiveChatMsg',async(event)=>{
    socket.emit('updateMsgStatus',event.id)
    // console.log('收到消息:', event)
    list.value.push(event)
    // 当发送/接受消息的时候滚动到底部
    scrollToBottom()
  })
})
// 滚动到底部
const scrollToBottom = async()=>{
  await nextTick(()=>{
      window.scrollTo(0,document.body.scrollHeight)
  })
}
onUnmounted(()=>{
  socket.close()
})
// 发送消息
const onSendText=(text:string)=>{
  // console.log('发送消息:', text)
  socket.emit('sendChatMsg',{
    from:store.user?.id,
    to:consult.value?.docInfo?.id,
    msgType:MsgType.MsgText,
    msg:{
      content:text
    }
  })
}

// 发送图片
const onSendImage =(image:Image)=>{
  // console.log('发送图片:', image)
  socket.emit('sendChatMsg',{
    from:store.user?.id,
    to:consult.value?.docInfo?.id,
    msgType:MsgType.MsgImage,
    msg:{
      picture:image,
    }
  })
}
// 下拉刷新
const loading = ref(false)
const time =ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))
const anRefresh = async()=>{
  // console.log('下拉刷新')
  socket.emit('getChatMsgList',20,time.value,consult.value?.id)
}
</script>
<template>
  <div class="room-page">
    <cp-nav-bar title="问诊室"></cp-nav-bar>
    <!-- 状态栏 -->
    <room-status :status="consult?.status" :countdown="consult?.countdown"></room-status>
    <!-- 消息栏 -->
    <van-pull-refresh v-model="loading" @refresh="anRefresh">
      <room-message v-for="item in list" :key="item.id" :item="item"></room-message>

    </van-pull-refresh>
    <!-- 操作栏 -->
    <room-action
      @send-image="onSendImage"
    @send-text="onSendText" :disabled="consult?.status !== OrderType.ConsultChat"></room-action>
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
